from lib.clock import rtc_clock, custom_timer
from lib.sensors.oled import ops
from machine import Timer
from utils import common
import framebuf
from lib.sensors import dht11
import lib.net.wifi as wifi
import esp32
from lib.api import codemao

p0 = bytearray([0x18, 0x24, 0x24, 0x18, 0x00, 0x00, 0x00, 0x00])
fb0 = framebuf.FrameBuffer(p0, 8, 8, framebuf.MONO_HLSB)

# oled config
oled_config = common.get_config_value("sensors", 0)
scl = oled_config["scl"]
sda = oled_config["sda"]
width = oled_config["width"]
height = oled_config["height"]

# dht config
dht_config = common.get_config_value("sensors", 1)
dht_pin = dht_config["pin"]
temp = -1
humidity = -1
mcu_temp = -1

c_timer1 = custom_timer.CustomTimer(12 * 3600)
c_timer2 = custom_timer.CustomTimer(12)
tim0 = Timer(0)
tim1 = Timer(1)

sync_inteval = 60 * 1000 * 60 * 12
_oled = ops.init_oled(scl, sda, width, height)


def show_dht11():
    global _oled, temp, humidity
    ops.rect(0, 24, 128, 30, 0)
    y = 24
    ops.text("t: " + str(temp), 0, y)
    _oled.blit(fb0, 45, y)
    ops.text("C", 52, y)
    ops.text("h: " + str(humidity) + "%", 72, y)
    ops.show()


def show_time():
    # print(clock.get_date_str(),clock.get_time_str())
    ops.rect(0, 0, 128, 20, 0)
    # print(clock.get_time_str())
    ops.text(clock.get_date_str(), 0, 0)
    ops.text(clock.get_time_str(), 0, 12)
    ops.text("mcu:" + str(mcu_temp), 75, 12)
    ops.show()


def get_dht11():
    global temp, humidity, mcu_temp
    try:
        (temp, humidity) = dht11.readDHT11(dht_pin)
        mcu_temp = esp32.mcu_temperature()
    except Exception as e:
        print(e)


def show():
    show_time()
    show_dht11()

    # 同步时间
    if c_timer1.check():
        clock.sync_network_time()

    # 上传到codemao
    if c_timer2.check():
        data = f"温度:{temp}°C,湿度:{humidity}%,芯片温度:{mcu_temp}°C"
        codemao.upload_data(data)


def run():
    # time
    global clock
    clock = rtc_clock.RTC_CLOCK()
    wifi.do_connect_wifi()
    clock.sync_network_time()
    tim0.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: show())
    tim1.init(period=4000, mode=Timer.PERIODIC, callback=lambda t: get_dht11())


if __name__ == "__main__":
    run()
